package com.clippick;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.RectF;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import co.kr.clippick.R;

import com.clippick.common.GlobalValue;
import com.clippick.common.ImageLoader;
import com.clippick.common.Utils;
import com.clippick.database.DrawableManager;
import com.clippick.database.FeedOrderDBAdapter;
import com.clippick.database.HistoryDBAdapter;

@TargetApi(13)
public class ClipAdapter extends BaseAdapter {

	// common
	private Context mContext;
	private NewMainActivity activity;

	// controller
	private ImageLoader imageLoader;
	private DrawableManager manager;

	// view
	private LayoutInflater inflater;
	private ListView list;
	private View v;
	private ClipHolder h;

	// convert pixel to dp to give margin to imageView
	private int margins = 0;

	// clip data
	private List<Map> result = new ArrayList<Map>();

	public ClipAdapter(Context context) {
		mContext = context;
		activity = (NewMainActivity) mContext;
		inflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		imageLoader = new ImageLoader(mContext);
		manager = new DrawableManager();

		margins = (int) Utils.convertDpToPixel(5, mContext);
	}

	public void addClipData(List<Map> data) {
		result = data;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method
		return result.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return result.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	public boolean isImagePreView(int position) {
		if (result.get(position).get("preview").equals("true")) {
			return true;
		} else {
			return false;
		}
	}

	@TargetApi(13)
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.clip_row, parent, false);

			h = new ClipHolder();
			h.layout = (LinearLayout) convertView
					.findViewById(R.id.contentAddView);
			h.buttonsLayout = (LinearLayout) convertView
					.findViewById(R.id.button_layer);
			h.starImageLayer = (LinearLayout) convertView
					.findViewById(R.id.star_image_layout);

			h.starImage = (ImageView) convertView.findViewById(R.id.star_image);

			h.copyButton = (Button) convertView.findViewById(R.id.copy_button);
			h.shareButton = (Button) convertView
					.findViewById(R.id.share_button);
			h.deleteButton = (Button) convertView
					.findViewById(R.id.delete_button);

			h.info = (TextView) convertView.findViewById(R.id.clip_info);

			h.image = (ImageView) convertView.findViewById(R.id.content_image);
			h.text = (TextView) convertView.findViewById(R.id.texts);
			h.webTitle = (TextView) convertView.findViewById(R.id.web_title);
			h.webUrl = (TextView) convertView.findViewById(R.id.web_url);

			convertView.setTag(h);
			h.layout.setFocusable(false);

			h.layout.setFocusableInTouchMode(false);

		} else {
			h = (ClipHolder) convertView.getTag();
		}

		h.image.setVisibility(View.GONE);
		h.text.setVisibility(View.GONE);
		h.webTitle.setVisibility(View.GONE);
		h.webUrl.setVisibility(View.GONE);

		final Map<?, ?> item = result.get(position);

		boolean isPreView = Boolean
				.parseBoolean(item.get("preview").toString());
		String imagePath = "";

		if (item.get(FeedOrderDBAdapter.KEY_DB_TEXT_PATH) != null) {
			imagePath = item.get(FeedOrderDBAdapter.KEY_DB_TEXT_PATH)
					.toString();

			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
					(int) Utils.convertDpToPixel(50, mContext));
			params.setMargins(0, margins, margins, 0);

			if (imagePath.contains(GlobalValue.CLIPPICK_IMAGE_ROOT_FOLDER)) {
				// content: image only
				h.image.setAdjustViewBounds(true);
				h.image.setVisibility(View.GONE);

				if (isPreView) {
					h.image.setScaleType(ScaleType.CENTER);
				} else {
					params = new LayoutParams(LayoutParams.MATCH_PARENT,
							LayoutParams.MATCH_PARENT);
					params.setMargins(0, margins, margins, 0);
					h.image.setScaleType(ScaleType.FIT_CENTER);
				}

				h.image.setLayoutParams(params);
				imageLoader.showImage(imagePath, h.image, 1);

				h.image.setVisibility(View.VISIBLE);
			} else {
				// content: text only
				h.text.setText(imagePath);

				if (isPreView) {
					params = new LayoutParams(LayoutParams.MATCH_PARENT,
							(int) Utils.convertDpToPixel(50, mContext));

					h.text.setMaxLines(4);
				} else {
					params = new LayoutParams(LayoutParams.MATCH_PARENT,
							LayoutParams.WRAP_CONTENT);

					h.text.setMaxLines(9999);
				}

				h.text.setLayoutParams(params);
				h.text.setVisibility(View.VISIBLE);
			}
		}

		String dateText = item.get(HistoryDBAdapter.KEY_DB_DATE).toString();
		String deviceText = item.get(HistoryDBAdapter.KEY_DB_DEVICE).toString();

		String info = this.orginizeInfoText(dateText, deviceText);

		h.info.setVisibility(View.VISIBLE);
		h.info.setText(info);

		boolean isStar = false;
		if (item.get(HistoryDBAdapter.KEY_DB_KEEPBOX).equals("1")) {
			isStar = true;
		}

		if (isStar) {
			h.starImage.setImageDrawable(mContext.getResources().getDrawable(
					R.drawable.star_a));
		} else {
			h.starImage.setImageDrawable(mContext.getResources().getDrawable(
					R.drawable.star_n));
		}

		if (isPreView) {
			h.buttonsLayout.setVisibility(View.GONE);
		} else {
			h.buttonsLayout.setVisibility(View.VISIBLE);
		}

		// set actions:
		h.deleteButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				activity.deleteClip(item.get(HistoryDBAdapter.KEY_DB_NO)
						.toString());
			}
		});

		h.shareButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				activity.shareClip(item);
			}
		});

		h.copyButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				activity.copyContent(item);
			}
		});
		
		h.starImage.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				activity.setActiveOrInactiveStar(item);
			}
		});
		
		h.starImageLayer.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				activity.setActiveOrInactiveStar(item);
			}
		});

		return convertView;
	}

	private final int getScreenWidth() {
		Display display = activity.getWindowManager().getDefaultDisplay();
		Point size = new Point();
		display.getSize(size);
		return size.x;
	}

	private final String orginizeInfoText(String dateText, String deviceText) {
		// date format
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date testDate = null;
		try {
			testDate = sdf.parse(dateText);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		SimpleDateFormat formatter = new SimpleDateFormat("MMMM dd, hh:mm a");
		String newFormat = formatter.format(testDate);

		StringBuilder builder = new StringBuilder();
		builder.append("Clipped on ").append(newFormat).append(" from ")
				.append(deviceText);
		return builder.toString();
	}

	OnClickListener imageListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			activity.showImageFullScreen((Map) v.getTag());
		}
	};

	public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
		int sourceWidth = source.getWidth();
		int sourceHeight = source.getHeight();

		// Compute the scaling factors to fit the new height and width,
		// respectively.
		// To cover the final image, the final scaling will be the bigger
		// of these two.
		float xScale = (float) newWidth / sourceWidth;
		float yScale = (float) newHeight / sourceHeight;
		float scale = Math.max(xScale, yScale);

		// Now get the size of the source bitmap when scaled
		float scaledWidth = scale * sourceWidth;
		float scaledHeight = scale * sourceHeight;

		// Let's find out the upper left coordinates if the scaled bitmap
		// should be centered in the new size give by the parameters
		float left = (newWidth - scaledWidth) / 2;
		float top = (newHeight - scaledHeight) / 2;

		// The target rectangle for the new, scaled version of the source bitmap
		// will now
		// be
		RectF targetRect = new RectF(left, top, left + scaledWidth, top
				+ scaledHeight);

		// Finally, we create a new bitmap of the specified size and draw our
		// new,
		// scaled bitmap onto it.
		Bitmap dest = Bitmap.createBitmap(newWidth, newHeight,
				source.getConfig());
		Canvas canvas = new Canvas(dest);
		canvas.drawBitmap(source, null, targetRect, null);

		return dest;
	}

	public void showButtonLayer(boolean value) {
		if (value) {
			h.buttonsLayout.setVisibility(View.VISIBLE);
		} else {
			h.buttonsLayout.setVisibility(View.GONE);
		}
	}

	public class ClipHolder {
		public LinearLayout layout;
		public LinearLayout buttonsLayout;
		public LinearLayout starImageLayer;
		public Button copyButton;
		public Button shareButton;
		public Button deleteButton;
		public ImageView starImage;
		public TextView info;
		public ImageView image;
		public ImageView smallImageView;
		public TextView webTitle;
		public TextView webUrl;
		public TextView text;
	}
}
